<template>
  <div class="spec-preview">
    <img :src="imgUrl" />
    <div class="event" @mousemove="ZoomImg"></div>
    <div class="big">
      <img :src="imgUrl" ref="bigImg" v-if="imgUrl" />
    </div>
    <div class="mask" ref="mark"></div>
  </div>
</template>

<script>
export default {
  name: "Zoom",
  props: ["skuDefaultImg"],
  mounted() {
    this.$bus.$on("changeImg", (imgUrl) => {
      this.imgUrl = imgUrl;
    });
  },
  methods: {
    ZoomImg(e) {
      const mark = this.$refs.mark; //放大镜盒子
      const bigImg = this.$refs.bigImg;
      // console.log(e.offsetX);
      // 获取鼠标在蒙版移动的位置
      const event = {
        x: e.offsetX,
        y: e.offsetY,
      };

      // 获取放大镜盒子宽高一半
      const markWH = {
        w: mark.offsetWidth / 2,
        h: mark.offsetHeight / 2,
      };

      // 放大镜盒子移动的距离  鼠标移动距离-盒子宽高一半
      const markMove = {
        x: event.x - markWH.w,
        y: event.y - markWH.h,
      };

      // 设置边界值

      // 放大镜盒子最大移动距离
      const markMax = {
        x: e.target.clientWidth - mark.clientWidth,
        y: e.target.clientHeight - mark.clientHeight,
      };

      if (markMove.x <= 5) {
        markMove.x = 0;
      } else if (markMove.x >= markMax.x) {
        markMove.x = markMax.x;
      }

      if (markMove.y <= 5) {
        markMove.y = 0;
      } else if (markMove.y >= markMax.y) {
        markMove.y = markMax.y;
      }

      // 放大镜盒子移动
      mark.style.left = markMove.x + "px";
      mark.style.top = markMove.y + "px";

      // 放大图移动的距离
      if (!bigImg) return;
      bigImg.style.left = -markMove.x * 2 + "px";
      bigImg.style.top = -markMove.y * 2 + "px";
    },
  },
  data() {
    return {
      imgUrl: "",
    };
  },
  watch: {
    skuDefaultImg(newUrl) {
      this.imgUrl = newUrl;
    },
  },
};
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>
